package com.zkjl.protect_business.controller;


import cn.hutool.core.util.IdUtil;
import com.zkjl.protect_business.common.ApiResponse;
import com.zkjl.protect_business.common.Status;
import com.zkjl.protect_business.common.SystemLog;
import com.zkjl.protect_business.common.UserThreadLocal;
import com.zkjl.protect_business.dto.LoginRequest;
import com.zkjl.protect_business.entity.Log;
import com.zkjl.protect_business.entity.Permission;
import com.zkjl.protect_business.entity.User;
import com.zkjl.protect_business.exception.SecurityException;
import com.zkjl.protect_business.repository.LogRepository;
import com.zkjl.protect_business.repository.UserRepository;
import com.zkjl.protect_business.service.PermissionService;
import com.zkjl.protect_business.utils.JwtUtil;
import com.zkjl.protect_business.vo.JwtResponse;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import java.util.List;

import static com.zkjl.protect_business.common.Consts.LOG_TYPE_BUSINESS_OPERATION;
import static com.zkjl.protect_business.common.Consts.LOG_TYPE_LOGIN;

/**
 * <p>
 * 认证 Controller，包括用户注册，用户登录请求
 * </p>
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
@Api(tags = {"登录鉴权相关"})
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    UserRepository userRepository;
    @Autowired
    LogRepository logRepository;
    @Autowired
    PermissionService permissionService;

    /**
     * 登录
     */
    @PostMapping("/login")
    @SystemLog(description = "登录",type = LOG_TYPE_LOGIN)
    public ApiResponse login(@Valid @RequestBody LoginRequest loginRequest) {
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUserName(), loginRequest.getPassWord()));

        SecurityContextHolder.getContext()
                .setAuthentication(authentication);

        Object principal = authentication.getPrincipal();

        User user = userRepository.findByUserName(loginRequest.getUserName());

        //登录成功
        UserThreadLocal.set(user);//将user对象放置在本地线程中，方便controller和service获取

        String jwt = jwtUtil.createJWT(authentication,loginRequest.getRememberMe());
        return ApiResponse.ofSuccess(new JwtResponse(jwt, principal));
    }

    @PostMapping("/logout")
    public ApiResponse logout(HttpServletRequest request) {
        try {

            Log log = new Log();
            log.setId(IdUtil.simpleUUID());
            log.setName("退出登录");
            log.setLogType(LOG_TYPE_LOGIN);

            User user = UserThreadLocal.get();
            if (user != null) {
                log.setBaseInfo();
            }
            Log save = logRepository.save(log);

            // 设置JWT过期
            jwtUtil.invalidateJWT(request);
        } catch (SecurityException e) {
            throw new SecurityException(Status.UNAUTHORIZED);
        }
        return ApiResponse.ofStatus(Status.LOGOUT);
    }
}
